'use strict'

let
    router = require('koa-router')(),
    fs = require('fs'),
    path = require('path');


// 查找除 index.js 外的所有真正的路由文件
function searchRoutes(dir) {

    let files = fs.readdirSync(dir);

    let routerFile = files.filter(fileName => {
        return fileName.endsWith('.js') && fileName !== 'index.js'
    });

    return routerFile
};


// 注册 路由 
function registerRoutes(files,dir) {

    files.forEach(item => {

        let tmpFile = path.join(dir,item);

        let tmpRoutes = require(tmpFile);

        for (let i in tmpRoutes) {
            let type = tmpRoutes[i][0];
            let fn = tmpRoutes[i][1];
            if (type === 'get') {
                router.get(i, fn)
            } else if (type === 'post') {
                router.post(i, fn)
            }
        }

    });

};


// 暴露模块 返回注册完的真正路由文件
module.exports = function () {

    let dir = __dirname;

    let files = searchRoutes(dir);

    registerRoutes(files,dir);

    return router.routes();
};